<?php	

	define('ChartType','Pie');
	
	if (isset($_POST['Category'])) {
		
		include_once('../../config.php'); 
		session_start();
		LinkDataBase();
		$Array_Field = FieldLocationGet($_POST['Category']);
				
		$Field = implode(", ",$Array_Field);
		//Find question.
		$sql = "select ".$_POST['filename'].".table_name AS table_name, item, total, ".$Field." 
				FROM ".$_POST['filename']." LEFT JOIN sheet 
				ON ".$_POST['filename'].".table_name = binary(sheet.table_name) 
				WHERE table_number='".$_POST['tablename']."' AND 
				item NOT LIKE '%Base: All Respondents%' AND 
				item NOT LIKE '%Base: Respondents%'";
		
		$result= mysql_query($sql);
		$numResult = mysql_num_rows($result);
		
		if ($numResult==0)
			return;
		?>
                
		<script type="text/javascript">
        var sub_QAname = '';

        var myrow = new Array();
        var RowTitle = new Array();
		var mycolumns = new Array();
        <?php
        
        $item = "";
        $index = 0;
        $z = 0;
        while($row = mysql_fetch_assoc($result)) {
            
            //Find Column name and define array.
            if ($row['total']=='Total') {
				$TableQAName = str_replace("'","\'",$row['table_name']);
                for ($i=0; $i<count($Array_Field); $i++) {
                ?>
                    var DB_title = '<?php echo $row[$Array_Field[$i]];?>';
                    console.log(DB_title);
                    RowTitle.push(DB_title);
                <?php
                }
            }
            
            
            if ((($item!="")&&($row['item']!='Sigma')&&
                (strpos($row['total'],'%'))&&
                ($_POST['keyword']==''))||
                //For keyword exists.
                (($item!="")&&($row['item']!='Sigma')&&
                (strpos($row['total'],'%'))&&
                ($_POST['keyword']!='')&&
                //contain is YES.
                (((strpos($item,(string)$_POST['keyword']))&&
                ($_POST['contain']=='YES'))||
                //contain is NO.
                ((!strpos($item,(string)$_POST['keyword']))&&
                ($_POST['contain']=='NO'))))) {
                    
                    
                    
                //Check type and Catch next question info for javascript.
                if (isset($_POST['Array_SubXML']['sub_QAname'])) {
                    if (is_array($_POST['Array_SubXML']['sub_QAname'])) {
                    ?>
                        sub_QAname = '<?php echo $_POST['Array_SubXML']['sub_QAname'][$index]; ?>\n';
                    <?php
                        $index++;
                    }
                    else {
                    ?>
                        sub_QAname = '<?php echo $_POST['Array_SubXML']['sub_QAname']; ?>\n';
                    <?php
                    }
                }
                ?>
                var index = <?php echo $z;?>;
                myrow[index] = new Array();
                
                var ItemName = '<?php echo str_replace("'","\'",str_replace('(Net)','',$item)); ?>';
				
                if ((ItemName!='No')&&(sub_QAname!=''))
                    ItemName = ItemName+' - '+sub_QAname;
                
                myrow[index].push(ItemName);
				mycolumns.push(ItemName);
                <?php
                for ($i=0; $i<count($Array_Field); $i++) {
                    
                    //Check row is percent or not percent.
                    if (strpos($row[$Array_Field[$i]], '%')!==false)
                        $value = str_replace('%','',$row[$Array_Field[$i]])/100;
                    else
                        $value = '0.00';
                    
                ?>
                    var value = <?php echo $value; ?>;
                    myrow[index].push(value);
                    myrow[index].push(sub_QAname+Math.round(value*100)+'%');
                <?php
                }
                $z++;
            }
            else if ($row['item']=='Sigma')
                break;
                        
            $item = $row['item'];
        }
        ?>
        var Array_Chart = new Array();
        <?php
        for ($i=0; $i<count($Array_Field); $i++) {
        ?>
            var index = <?php echo $i;?>;
            
            var data = new google.visualization.DataTable();
            data.addColumn('string');
            data.addColumn('number');
            data.addColumn({type: 'string', role: 'tooltip'});
            for (var i=0; i<myrow.length; i++)
                data.addRow([myrow[i][0],myrow[i][1+index*2],myrow[i][2+index*2]]);
            
            var options = {
            title: RowTitle[index],	
            legend: {position: 'none'},
            vAxis: {textPosition:'out', maxValue:1, minValue:0, format:'#%'},
            height: '100%',
            tooltip: {text: 'percentage', showColorCode: 'true'},
			backgroundColor: 'none'
            };
                
            Array_Chart[index] = new google.visualization.PieChart(document.getElementById('chart_div<?php echo $i; ?>'));
            Array_Chart[index].draw(data, options);
            
            if (sub_QAname!='') {	
                //Handle event.
                google.visualization.events.addListener(Array_Chart[index], 'select', selectHandler(data, Array_Chart[index]));
            }
            
        <?php
        }
        ?>
        
        function selectHandler(data, chart) {
            return function(){
				
				//Catch location of click.
				var selection = chart.getSelection();
				var message = selection[0];
				var index = message.row;	
				var LegendName = mycolumns[index];
				
				//Check type and Catch next question info for javascript.
				var sub_table = '';
				var sub_ChartType = '';
				var KeyWord = '';
				var Contain = '';
				var Xaxis = '';
                
                //if cancel selection, Stop crash.
                if (message==null)
                    return;
                
                var str = data.getValue(message.row, 0);
                
                //Stop that select No, click to next question.
                if (str=='No')
                    return;	
                        
                <?php
				if (isset($_POST['Array_SubXML']['sub_table'])) {
					if (is_array($_POST['Array_SubXML']['sub_table'])) {
				?>
						var Temp_Array_Table = <?php echo json_encode($_POST['Array_SubXML']['sub_table']); ?>;
						var Temp_Array_ChartType = <?php echo json_encode($_POST['Array_SubXML']['sub_charttype']); ?>;
						var Temp_Array_KeyWord = <?php echo json_encode($_POST['Array_SubXML']['sub_keyword']); ?>;
						var Temp_Array_Contain = <?php echo json_encode($_POST['Array_SubXML']['sub_contain']); ?>;
						var Temp_Array_Xaxis = <?php echo json_encode($_POST['Array_SubXML']['sub_Xaxis']); ?>;
	
						sub_table = Temp_Array_Table[index];
						sub_ChartType = Temp_Array_ChartType[index];
						KeyWord = Temp_Array_KeyWord[index];
						Contain = Temp_Array_Contain[index];
						Xaxis = Temp_Array_Xaxis[index];
				<?php
					}
					else {
				?>
						sub_table = '<?php echo $_POST['Array_SubXML']['sub_table']; ?>';
						sub_ChartType = '<?php echo $_POST['Array_SubXML']['sub_charttype']; ?>';
						KeyWord = '<?php echo $_POST['Array_SubXML']['sub_keyword']; ?>';
						Contain = '<?php echo $_POST['Array_SubXML']['sub_contain']; ?>';
                    	Xaxis = '<?php echo $_POST['Array_SubXML']['sub_Xaxis']; ?>';
				<?php
					}
				}
				?>
					
				var TableName = '<?php echo $_POST['tablename']; ?>';
				var year = '<?php echo $_POST['year']; ?>';
				var season = '<?php echo $_POST['season']; ?>';
				var type = '<?php echo $_POST['type']; ?>';
				var Step = <?php echo $_POST['step']; ?>;
                    
                //Check previous title is array or string.
                var Previous_Title = new Array();
                <?php
                if (is_array($_POST['previous_title'])) {
                ?>
                    Previous_Title = <?php echo json_encode($_POST['previous_title']); ?>;
                <?php
                }
                else {
                ?>
                    Previous_Title.push('<?php echo $_POST['previous_title']; ?>');
                <?php
                }
                ?>
				var Temp = new Array('<a href="#" id="'+Step+'" name="'+TableName+'" class="'+ChartType+'" onclick="GotoTargetLocation(this);" >'+LegendName+'</a>',
				'<?php echo $_POST['tablename']; ?>', '<?php echo ChartType; ?>', '<?php echo $_POST['keyword']; ?>', '<?php echo $_POST['contain']; ?>', '<?php echo $_POST['Xaxis']; ?>');
				Previous_Title.push(Temp);
					
				$("#content-detail").load('../chart/detail/index.php',
				{'year':year, 'season':season, 'type':type, 'tablename': sub_table, 'charttype': sub_ChartType, 
				'keyword': KeyWord, 'contain': Contain, 'Xaxis': Xaxis, 'step': Step+1, 'previous_title': Previous_Title});
            }
        }
        
		$("#legend_div").load('../chart/detail/Legend.php', {'Array_LegendText': mycolumns});
        
     </script>
     

<style type="text/css">
#background_div {
	background-image:url('../images/graphBG.png');
    background-size: cover;
	-moz-background-size: 100% 100%;
	-o-background-size: 100% 100%;
	-webkit-background-size: 100% 100%; 
	background-size: 100% 100%;
}
</style>
<?php
	}
	
	//Created chart frame by count of category.
	for ($i=1; $i<count($Array_Field)+1; $i++) {
		
		if ($i%2===0) {
			$ClassName = 'tablegeneric';
			$CSSLocation = 'padding: 0 20px 0 20px';
			$addFrontHtml = '';
			$addBackHtml = '</tr>';
		}
		else {
			$ClassName = 'tablegenericleft'; 
			$CSSLocation = 'margin-left: 0px';
			$addFrontHtml = '<tr>';
			$addBackHtml = '';
		}
		$table .= $addFrontHtml.'<td><table width="300" border="1" cellspacing="0" cellpadding="0" class="'.$ClassName.'" style="'.$CSSLocation.'">
<div id="chart_div'.($i-1).'" style="width: 400; height:200; margin-top:50px"></div></table></td>'.$addBackHtml;
	}
	
	if ((count($_POST['Array_SubXML'])!=0)&&(count($_POST['Array_SubXML'])!=1))
		$div = 'background_div';
	else
		$div = '';
?>
<div id="<?php echo $div; ?>" style="width: 770;" class="right-image">
<div>
<table>

 <?php echo $table; ?>

</table>
</div><br/>
</div><br/>
<div id="legend_div" style="width: 770;margin-bottom:30px;" class="right-image"></div>